﻿Imports TNCDAL
Imports TNCBAL
Imports System.Data.Linq
Imports HTLibrary
Public Class ucSellingHBL
    Private _idHBL As Integer
    Dim ctrlHBL As New CHBLController
    Private hbl As tblHBL = Nothing
    Private ctrlSelling As New CSellingRateController()
    Private arrEdit As New ArrayList()
    Private ctrlHblExchage As New CHblExchangesController
   
    Public Sub New()

        ' This call is required by the designer.
        InitializeComponent()

        ' Add any initialization after the InitializeComponent() call.

    End Sub
    Public Sub New(ByVal idHBL As Integer)

        ' This call is required by the designer.
        InitializeComponent()
        DataGridViewHelper.DataGridView_InitEvent(gridSelling)
        ' Add any initialization after the InitializeComponent() call.
        _idHBL = idHBL
        hbl = ctrlHBL.SelectRecordByID(_idHBL)
    End Sub

    Private Sub ucSellingHBL_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
        'lấy thông tin tiền tệ
        LayThongTinTienTe()
        'check cước xem đã có hay chưa
        Dim mBuying As New MBuyingRate
        'Sau khi kiểm tra giá cước, nếu mà có giá cước rồi thì mới chạy các bước tiếp theo không thì quay lại
        If mBuying.ExistCuocCont(hbl.tblFileMBL.tblFile.ID_File) = False Then
            MessageBox.Show("Chưa có bảng giá cước selling")
            Return
        End If
        'lấy thông tin sellings
        BindGridSelling()
        EnableControls(False)
    End Sub
    Public Sub LayThongTinTienTe()
        ''lấy ra loại tiền VND        
        'Dim ctrlCurrency As New MCurrencies
        'currencyVND = ctrlCurrency.GetCurrencyByCode("VND")
        'currencyForeign = ctrlCurrency.GetCurrencyByID(hbl.tblFileMBL.tblFile.ID_Currency)
        'Dim listCurrency As New List(Of tblCurrency)
        'If (currencyVND IsNot Nothing) Then
        '    listCurrency.Add(currencyVND)
        'End If
        'If (currencyForeign IsNot Nothing) Then
        '    listCurrency.Add(currencyForeign)
        '    lblForeignCurrency.Text = "1 " & currencyForeign.Code & " = "
        'Else
        '    lblForeignCurrency.Text = "1 VND = "
        'End If
        'cboCurrency.DataSource = listCurrency
        'cboCurrency.DisplayMember = "Code"
        'cboCurrency.ValueMember = "ID_Currency"
        'If (cboCurrency.Items.Count > 0) Then
        '    cboCurrency.SelectedIndex = 0
        'End If
        'Try
        '    txtRatio.Text = hbl.Ratio.Value.ToString("#,##0.##")
        'Catch ex As Exception
        '    txtRatio.Text = "1"
        'End Try
    End Sub
    Public Sub BindGridSelling()
        arrEdit.Clear()
        If (ctrlSelling.CheckExistSellingHBL(_idHBL) = False) Then
            ctrlSelling.HoTroTinhSellingRate(_idHBL, hbl.tblFileMBL.tblFile.IsFCL)
        Else
            ctrlSelling.ModifySellingRate(_idHBL, hbl.tblFileMBL.tblFile.IsFCL)
        End If
        CViewer.BindGridSelling(gridSelling, _idHBL, cboCurr)
        'Dim sellings = ctrlSelling.GetSellingRateList2(_idHBL)
        'gridSelling.DataSource = sellings
        'FormatGridview()
        CalculateTotalSelling()
    End Sub
    Public Sub ReCompute()
        EnableControls(False)
        ctrlSelling.RefreshData()
        ctrlSelling.HoTroTinhSellingRate(_idHBL, hbl.tblFileMBL.tblFile.IsFCL)
        CViewer.BindGridSelling(gridSelling, _idHBL, cboCurr)
        ctrlHblExchage.RefreshData()
        CalculateTotalSelling()
    End Sub
    Private Sub CalculateTotalSelling()
        Dim total As Double = 0
        For i As Integer = 0 To gridSelling.Rows.Count - 1
            Try
                Dim priceCurrency As Integer = CInt(gridSelling.Rows(i).Cells("cboCurr").Value.ToString)
                Dim price As Double = CDbl(gridSelling.Rows(i).Cells("Price").Value)
                Dim ratio As Double = ctrlHblExchage.GetRatioOfCur(priceCurrency, _idHBL)
                total += price * ratio
            Catch ex As Exception
            End Try
        Next
        lblTotal.Text = total.ToString("#,##0.##")
    End Sub
    Private Sub EnableControls(ByVal val As Boolean)
        'txtRatio.Enabled = val
        gridSelling.ReadOnly = Not val
        gridSelling.Columns("Price").ReadOnly = True
        gridSelling.Columns("FeeName").ReadOnly = True
        'gridSelling.Columns("Code").ReadOnly = True
    End Sub
    Private Sub EnableExControls(ByVal val As Boolean)
        gridExchange.ReadOnly = Not val
    End Sub
    Private Sub gridSelling_CellEndEdit(ByVal sender As System.Object, ByVal e As System.Windows.Forms.DataGridViewCellEventArgs) Handles gridSelling.CellEndEdit
        Select Case e.ColumnIndex
            Case 1, 2
                'tự động cập nhật lại giá trị của price
                Try
                    Dim UnitPrice As Double = Double.Parse(gridSelling.Rows(e.RowIndex).Cells("UnitPrice").Value.ToString)
                    Dim Quantity As Double = Double.Parse(gridSelling.Rows(e.RowIndex).Cells("Quantity").Value.ToString)
                    Dim total As Double = UnitPrice * Quantity
                    gridSelling.Rows(e.RowIndex).Cells("Price").Value = total
                Catch ex As Exception
                    gridSelling.Rows(e.RowIndex).Cells("Price").Value = ""
                End Try
        End Select
        'cập nhật lại tổng
        CalculateTotalSelling()
        If (arrEdit.Contains(e.RowIndex) = False) Then
            arrEdit.Add(e.RowIndex)
        End If
    End Sub
    Public Sub EditSellingRate()
        EnableControls(True)
    End Sub
    Public Sub CancelSellingRate()
        BindGridSelling()
        EnableControls(False)
    End Sub
    Public Sub SaveSellingRate()
        'lưu lại những dòng đã Edit
        For Each i As Integer In arrEdit
            'lấy ra ID_SellingFee của nó
            Dim fileFee As tblSellingFee
            If (gridSelling.Rows(i).Cells("ID_SellingFee").Value IsNot Nothing) Then
                'cập nhật
                fileFee = ctrlSelling.SelectRecordByID(Integer.Parse(gridSelling.Rows(i).Cells("ID_SellingFee").Value.ToString))
                If (fileFee IsNot Nothing) Then
                    With fileFee
                        .UnitPrice = CDbl(gridSelling.Rows(i).Cells("UnitPrice").Value)
                        .Quantity = CDbl(gridSelling.Rows(i).Cells("Quantity").Value)
                        .Price = CDbl(gridSelling.Rows(i).Cells("Price").Value)
                        .ID_Currency = CInt(gridSelling.Rows(i).Cells("cboCurr").Value)
                        .Description = gridSelling.Rows(i).Cells("Description").Value.ToString()
                    End With
                    ctrlSelling.UpdateRecordWithoutAttach(fileFee)
                End If
            End If
        Next
        'Cập nhật tỷ giá
        'If (txtRatio.Text <> "") Then
        '    hbl.Ratio = Double.Parse(txtRatio.Text)
        '    ctrlHBL.UpdateRecordWithoutAttach(hbl)
        'End If
        'sau khi cập nhật xong thì load lại
        EnableControls(False)
        BindGridSelling()
        'ghi log
        Dim objLogController As New LogController
        objLogController.Insert(enumAction.Edit, "Selling Rate of HBL " & hbl.HBLNo & " of File " & hbl.tblFileMBL.tblFile.FileNo)
    End Sub
    Public Property ID_HBL As Integer
        Get
            Return _idHBL
        End Get
        Set(ByVal value As Integer)
            _idHBL = value
        End Set
    End Property

    Private Sub btExchange_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btExchange.Click
        If (panelExchange.Visible = True) Then
            panelExchange.Visible = False
        Else
            panelExchange.Visible = True
        End If
    End Sub
    Private Sub EnableButtonsEx(ByVal val As Boolean)
        gridExchange.ReadOnly = val
        gridExchange.Columns("exCurr").ReadOnly = True
        Try
            gridExchange.CurrentCell = gridExchange.CurrentRow.Cells("exRatio")
        Catch ex As Exception
        End Try
        btnEdit.Enabled = val
        btnUpdate.Enabled = Not val
        btnCancel.Enabled = Not val
    End Sub
    Private Sub panelExchange_VisibleChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles panelExchange.VisibleChanged
        If (panelExchange.Visible = True) Then
            'load thông tin exchange
            Dim currentExchanges = ctrlHblExchage.GetHblExchange(_idHBL)
            gridExchange.DataSource = currentExchanges
            EnableButtonsEx(True)
        End If
    End Sub

    Private Sub btnCancel_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnCancel.Click
        panelExchange.Visible = False
    End Sub

    Private Sub btnUpdate_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnUpdate.Click
        'xoa het cai cu
        ctrlHblExchage.DeleteAllRecord(_idHBL)
        For Each r As DataGridViewRow In gridExchange.Rows
            Dim newEx As New tblHBLExchange
            newEx.ID_Currency = CInt(r.Cells("exID_Currency").Value)
            newEx.Ratio = CDbl(r.Cells("exRatio").Value)
            newEx.ID_HBL = _idHBL
            ctrlHblExchage.InsertRecord(newEx)
        Next
        'cập nhật lại tỷ giá
        CalculateTotalSelling()
        panelExchange.Visible = False
    End Sub

    Private Sub btnEdit_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnEdit.Click
        EnableButtonsEx(False)
    End Sub

    Private Sub btExClose_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btExClose.Click
        panelExchange.Visible = False
    End Sub

    Private Sub gridSelling_EditingControlShowing(ByVal sender As System.Object, ByVal e As System.Windows.Forms.DataGridViewEditingControlShowingEventArgs) Handles gridSelling.EditingControlShowing
        If gridSelling.CurrentCell.ColumnIndex = 1 Then
            'Desired Column
            Dim tb As TextBox = TryCast(e.Control, TextBox)
            If tb IsNot Nothing Then
                AddHandler tb.KeyPress, AddressOf Column1_KeyPress
                'tb.KeyPress += New KeyPressEventHandler(AddressOf Column1_KeyPress)
            End If
        End If
    End Sub
    Private Sub Column1_KeyPress(ByVal sender As Object, ByVal e As KeyPressEventArgs)
        If Not Char.IsControl(e.KeyChar) AndAlso Not Char.IsDigit(e.KeyChar) Then
            e.Handled = True
        End If
    End Sub
    Private Sub gridExchange_EditingControlShowing(ByVal sender As System.Object, ByVal e As System.Windows.Forms.DataGridViewEditingControlShowingEventArgs) Handles gridExchange.EditingControlShowing
        If gridExchange.CurrentCell.ColumnIndex = 2 Then
            'Desired Column
            Dim tb As TextBox = TryCast(e.Control, TextBox)
            If tb IsNot Nothing Then
                AddHandler tb.KeyPress, AddressOf Column1_KeyPress
                'tb.KeyPress += New KeyPressEventHandler(AddressOf Column1_KeyPress)
            End If
        End If
    End Sub
End Class
